package monster.com.cvh.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import monster.com.cvh.R;
import monster.com.cvh.application.TinkerApplicationLike;
import monster.com.cvh.bean.EducationBean;
import monster.com.cvh.bean.PickDataBean;
import monster.com.cvh.listener.OnHideKeyBoardListener;

/**
 * @author: 13580
 * @data: 2018/3/19
 * @function:教育经历adapter
 */

public class EducationAdapter extends BaseQuickAdapter<EducationBean.DataBean, BaseViewHolder> {
    private final Calendar mStartDate;
    private final Calendar mEndDate;
    private final Calendar mSelectedDate;
    private final ArrayList<PickDataBean> mDegreeTypeBeans;
    private TimePickerView mPvGradutaionTime;
    private TimePickerView mPvSchoolTime;
    private OptionsPickerView mPVDegreeType;
    private OnHideKeyBoardListener mListner;


    public EducationAdapter(@Nullable List<EducationBean.DataBean> data, OnHideKeyBoardListener listener) {
        super(R.layout.item_education, data);
        mSelectedDate = Calendar.getInstance();//系统当前时间
        mStartDate = Calendar.getInstance();
        mStartDate.set(1970, 0, 1);
        mEndDate = Calendar.getInstance();
        mEndDate.set(Calendar.YEAR, mEndDate.get(Calendar.YEAR) + 6);
        mListner = listener;
        mDegreeTypeBeans = new ArrayList<>();
        Context mContext = TinkerApplicationLike.getContext();
        mDegreeTypeBeans.add(new PickDataBean(mContext.getResources().getString(R.string.fragment_education_degree_secondary_school), 0));
        mDegreeTypeBeans.add(new PickDataBean(mContext.getResources().getString(R.string.fragment_education_degree_high_school), 1));
        mDegreeTypeBeans.add(new PickDataBean(mContext.getResources().getString(R.string.fragment_education_degree_junior_collage), 2));
        mDegreeTypeBeans.add(new PickDataBean(mContext.getResources().getString(R.string.fragment_education_degree_undergraduate), 3));
        mDegreeTypeBeans.add(new PickDataBean(mContext.getResources().getString(R.string.fragment_education_degree_master), 4));
        mDegreeTypeBeans.add(new PickDataBean(mContext.getResources().getString(R.string.fragment_education_degree_doctor), 5));

    }

    @Override
    protected void convert(final BaseViewHolder helper, final EducationBean.DataBean item) {
        String timeOfEnrolment = item.getEnroll_time();
        String graduationTime = item.getGraduate_time();
        String degree = item.getDegree();
        if (timeOfEnrolment.contains(".")) {
            String enrollTime = item.getEnroll_time();
            timeOfEnrolment = enrollTime.substring(0, 4) + "年" + enrollTime.substring(5, 7) + "月";
        }
        if (graduationTime.contains(".")) {
            String graduateTime = item.getGraduate_time();
            graduationTime = graduateTime.substring(0, 4) + "年" + graduateTime.substring(5, 7) + "月";
        }
        String schoolName = item.getSchool_name();
        String professionName = item.getMajor();

        if (schoolName == null) {
            schoolName = "";
        }
        if (professionName == null) {
            professionName = "";
        }

        EditText edtSchoolName = (EditText) helper.getView(R.id.edt_item_education_school_name);
        EditText edtProfessionName = (EditText) helper.getView(R.id.edt_item_education_profession);
        //防止notifyDataChange()导致值Editext重绘触发TextWatcher造成数据错乱
        if (edtSchoolName.getTag() instanceof TextWatcher) {
            edtSchoolName.removeTextChangedListener((TextWatcher) edtSchoolName.getTag());
        }
        if (edtProfessionName.getTag() instanceof TextWatcher) {
            edtProfessionName.removeTextChangedListener((TextWatcher) edtProfessionName.getTag());
        }
        edtSchoolName.setText(schoolName);
        edtProfessionName.setText(professionName);
        TextWatcher schoolNameWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                item.setSchool_name(s.toString().trim());
            }
        };
        TextWatcher professionNameWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                item.setMajor(s.toString().trim());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };
        edtProfessionName.addTextChangedListener(professionNameWatcher);
        edtSchoolName.addTextChangedListener(schoolNameWatcher);
        edtSchoolName.setTag(schoolNameWatcher);
        edtProfessionName.setTag(professionNameWatcher);

        if (timeOfEnrolment.isEmpty()) {
            helper.setText(R.id.tv_item_education_education_time_of_enrolment, mContext.getResources().getString(R.string.choose));
            helper.setTextColor(R.id.tv_item_education_education_time_of_enrolment, mContext.getResources().getColor(R.color.tip_title));
        } else {
            helper.setText(R.id.tv_item_education_education_time_of_enrolment, timeOfEnrolment);
            helper.setTextColor(R.id.tv_item_education_education_time_of_enrolment, mContext.getResources().getColor(R.color.tv_title));
        }
        if (graduationTime.isEmpty()) {
            helper.setText(R.id.tv_item_education_graduation_time, mContext.getResources().getString(R.string.choose));
            helper.setTextColor(R.id.tv_item_education_graduation_time, mContext.getResources().getColor(R.color.tip_title));
        } else {
            helper.setText(R.id.tv_item_education_graduation_time, graduationTime);
            helper.setTextColor(R.id.tv_item_education_graduation_time, mContext.getResources().getColor(R.color.tv_title));
        }
        if (degree.isEmpty()) {
            helper.setText(R.id.tv_item_education_education_degree, mContext.getResources().getString(R.string.choose));
            helper.setTextColor(R.id.tv_item_education_education_degree, mContext.getResources().getColor(R.color.tip_title));
        } else {
            helper.setText(R.id.tv_item_education_education_degree, degree);
            helper.setTextColor(R.id.tv_item_education_education_degree, mContext.getResources().getColor(R.color.tv_title));
        }

        helper.getView(R.id.rel_item_education_graduation_time).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListner.onHideKeyBoard();
                if (item.getGraduate_time() != null && item.getGraduate_time().contains(".")) {
                    String graduate_time = item.getGraduate_time();
                    mSelectedDate.set(Integer.parseInt(graduate_time.substring(0, 4)), Integer.parseInt(graduate_time.substring(5, 7)) - 1, 1);
                }
                initGraduationTime(helper, item);
            }
        });
        helper.getView(R.id.rel_item_education_time_of_enrolment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListner.onHideKeyBoard();
                if (item.getEnroll_time() != null && item.getEnroll_time().contains(".")) {
                    String enrollTime = item.getEnroll_time();
                    mSelectedDate.set(Integer.parseInt(enrollTime.substring(0, 4)), Integer.parseInt(enrollTime.substring(5, enrollTime.length())) - 1, 1);
                }
                initTimeOfEnrolment(helper);
            }
        });

        helper.getView(R.id.rel_item_education_degree).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListner.onHideKeyBoard();
                initPickDegree(helper, item);
            }
        });
        helper.setText(R.id.tv_item_education_title, mContext.getResources().getString(R.string.fragment_education_title) + (helper.getAdapterPosition() + 1));
        //如果只有一条item时，删除按钮不显示
        if (mData.size() == 1) {
            helper.setVisible(R.id.iv_item_education_delete, false);
        } else {
            helper.setVisible(R.id.iv_item_education_delete, true);
        }
        //当数据长度等3时，footer隐藏
        if (mData.size() == 3) {
            getFooterLayout().setVisibility(View.GONE);
        } else {
            getFooterLayout().setVisibility(View.VISIBLE);
        }
        //如果数据长度大于1，可以删除当前item
        helper.getView(R.id.iv_item_education_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mData.size() > 1) {
                    //初始化删除弹窗
                    AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                            .setMessage("是否删除教育经历" + (helper.getLayoutPosition() + 1) + "?")
                            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton(R.string.edt_info_delete, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mData.remove(helper.getLayoutPosition());
                                    notifyDataSetChanged();
                                    dialog.dismiss();
                                }
                            })
                            .create();
                    alertDialog.show();
                }
            }
        });
    }

    private void initPickDegree(final BaseViewHolder helper, final EducationBean.DataBean item) {
        mPVDegreeType = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String workType = mDegreeTypeBeans.get(options1).getPickerViewText();
                TextView tvDegree = (TextView) helper.getView(R.id.tv_item_education_education_degree);
                tvDegree.setText(workType);
                tvDegree.setTextColor(mContext.getResources().getColor(R.color.tv_title));
                item.setDegree(workType);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final ImageView ivSubmit = (ImageView) v.findViewById(R.id.iv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        ivSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPVDegreeType.returnData();
                                mPVDegreeType.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPVDegreeType.dismiss();
                            }
                        });
                    }
                })
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(mContext.getResources().getColor(R.color.line_color))
                .setLineSpacingMultiplier(2.0f)
                .setDecorView((ViewGroup) ((Activity) mContext).getWindow().getDecorView())
                .build();
        mPVDegreeType.setPicker(mDegreeTypeBeans);//添加数据
        int selecedIndex = getSelecedIndex(item.getDegree());
        mPVDegreeType.setSelectOptions(selecedIndex);
        mPVDegreeType.show();
    }

    private void initTimeOfEnrolment(final BaseViewHolder helper) {
        mPvSchoolTime = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = getTime(date);
                if (time == null) {
                    time = "";
                }
                helper.setText(R.id.tv_item_education_education_time_of_enrolment, time);
                helper.setTextColor(R.id.tv_item_education_education_time_of_enrolment, mContext.getResources().getColor(R.color.tv_title));
                mData.get(helper.getLayoutPosition()).setEnroll_time(time);
            }
        })
                .setDate(mSelectedDate)
                .setRangDate(mStartDate, mEndDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        TextView tvTitle = (TextView) v.findViewById(R.id.tv_pickerview_customer_launar_title);
                        final ImageView ivSubmit = (ImageView) v.findViewById(R.id.iv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvTitle.setText(mContext.getResources().getString(R.string.fragment_education_time_of_enrolment));
                        ivSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvSchoolTime.returnData();
                                mPvSchoolTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvSchoolTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, false, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(mContext.getResources().getColor(R.color.line_color))
                .setContentSize(20)
                .setLineSpacingMultiplier(2.0f)
                .setDecorView((ViewGroup) ((Activity) mContext).getWindow().getDecorView())
                .build();
        mPvSchoolTime.show();
    }

    private void initGraduationTime(final BaseViewHolder helper, EducationBean.DataBean item) {
        Calendar data = Calendar.getInstance();
        String enrollTime = item.getEnroll_time();
        if (!enrollTime.isEmpty()) {
            data.set(Integer.parseInt(enrollTime.substring(0, 4)), Integer.parseInt(enrollTime.substring(5, 7)) - 1, 1);
        } else {
            data = mStartDate;
        }

        mPvGradutaionTime = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String time = getTime(date);
                if (time == null) {
                    time = "";
                }
                helper.setText(R.id.tv_item_education_graduation_time, time);
                helper.setTextColor(R.id.tv_item_education_graduation_time, mContext.getResources().getColor(R.color.tv_title));
                mData.get(helper.getLayoutPosition()).setGraduate_time(time);
            }
        })
                .setDate(data)
                .setRangDate(data, mEndDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        TextView tvTitle = (TextView) v.findViewById(R.id.tv_pickerview_customer_launar_title);
                        final ImageView ivSubmit = (ImageView) v.findViewById(R.id.iv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvTitle.setText(mContext.getResources().getString(R.string.fragment_education_graduation_time));
                        ivSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvGradutaionTime.returnData();
                                mPvGradutaionTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPvGradutaionTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, false, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(mContext.getResources().getColor(R.color.line_color))
                .setContentSize(20)
                .setLineSpacingMultiplier(2.0f)
                .setDecorView((ViewGroup) ((Activity) mContext).getWindow().getDecorView())
                .build();
        mPvGradutaionTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }

    private Date string2Date(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        try {
            return format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检查信息完整性
     *
     * @return
     */
    public String checkInfoCompleted() {
        for (int i = 0; i < mData.size(); i++) {
            EducationBean.DataBean bean = mData.get(i);
            String timeOfEnrolment = bean.getEnroll_time();
            String graduationTime = bean.getGraduate_time();
            if (timeOfEnrolment != null && !timeOfEnrolment.isEmpty() &&
                    graduationTime != null && !graduationTime.isEmpty()
                    ) {
                Date graduationDate = string2Date(graduationTime);
                Date timeOfEnrolmentDate = string2Date(timeOfEnrolment);
                if (graduationDate != null && timeOfEnrolmentDate != null && timeOfEnrolmentDate.after(graduationDate)) {
                    return mContext.getResources().getString(R.string.fragment_education_pick_date_error);
                }
            }
        }
        return null;
    }

    private int getSelecedIndex(String content) {
        if (mDegreeTypeBeans != null) {
            for (int i = 0; i < mDegreeTypeBeans.size(); i++) {
                String name = mDegreeTypeBeans.get(i).getName();
                if (name.equals(content)) {
                    return i;
                }
            }
        }
        return 0;
    }
}
